package client;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextArea;

public class Client extends JFrame {

	private static final short GET = 1;

	private JPanel contentPane;
	
	private Socket s;
	private JTextField start;
	private JTextField end;
	private JTextArea info;
	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					test();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}
	
	private static void test() {
		Client frame = new Client();
		frame.setVisible(true);
		frame.linkToServer();
		
	}
	
	/**
	 * 连接到服务器
	 */
	public void linkToServer() {
		try {
			Socket s = new Socket("localHost", 12315);
			this.s = s;
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	
	/**
	 * Create the frame.
	 */
	public Client() {
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 450, 300);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentPane.setLayout(new BorderLayout(0, 0));
		setContentPane(contentPane);
		
		start = new JTextField();
		start.setText("开始行");
		contentPane.add(start, BorderLayout.NORTH);
		start.setColumns(10);
		
		end = new JTextField();
		end.setText("结束行");
		contentPane.add(end, BorderLayout.SOUTH);
		end.setColumns(10);
		JButton look = new JButton("查看");
		look.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String s = start.getText();
				String en = end.getText();
				int start_ = Integer.parseInt(s);
				int end_ = Integer.parseInt(en);
				
				info.setText(getFromServer(start_));
			}
		});
		contentPane.add(look, BorderLayout.EAST);
		
		info = new JTextArea();
		contentPane.add(info, BorderLayout.CENTER);
	}
	
	/**
	 * 从服务器获取第start , end行的数据
	 * @param start
	 * @param end
	 * @return
	 */
	private String getFromServer(int line) {
		Packet p = new Packet(GET);
		p.putInt(line);
		FromServer fs = p.send(s);
		return fs.getString();
	}
}
